// 个人结算页面
const app = getApp()

Page({
  data: {
    userInfo: null,
    roomInfo: null,
    settlementData: null,
    loading: false,
    hasSettlement: false
  },

  onLoad() {
    this.checkUserAndRoom()
  },

  onShow() {
    // 每次显示时重新检查
    this.checkUserAndRoom()
  },

  // 分享给好友
  async onShareAppMessage() {
    const ShareUtil = require('../../utils/shareUtil')
    return await ShareUtil.generateShareAppMessageConfig('settlement', {
      userInfo: this.data.userInfo,
      roomInfo: this.data.roomInfo,
      settlementData: this.data.settlementData
    })
  },

  // 分享到朋友圈
  async onShareTimeline() {
    const ShareUtil = require('../../utils/shareUtil')
    return await ShareUtil.generateShareTimelineConfig('settlement', {
      userInfo: this.data.userInfo,
      roomInfo: this.data.roomInfo,
      settlementData: this.data.settlementData
    })
  },

  // 检查用户和房间状态
  checkUserAndRoom() {
    const userInfo = wx.getStorageSync('userInfo') || app.globalData.userInfo
    const RoomCache = require('../../utils/roomCache')
    const roomData = RoomCache.getRoomBasicInfo()

    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        })
      }, 1500)
      return
    }

    if (!roomData) {
      wx.showModal({
        title: '结算失败',
        content: '房间信息不存在，请先加入房间',
        showCancel: false,
        confirmText: '确定',
        success: () => {
          wx.navigateBack({
            delta: 1
          })
        }
      })
      return
    }

    this.setData({
      userInfo: userInfo,
      roomInfo: roomData
    })

    // 获取结算数据
    this.getSettlementData()
  },

  // 获取结算数据
  getSettlementData() {
    if (!this.data.userInfo || !this.data.roomInfo) {
      console.log('缺少必要信息:', {
        hasUserInfo: !!this.data.userInfo,
        hasRoomInfo: !!this.data.roomInfo
      })
      return
    }

    console.log('开始获取结算数据:', {
      userId: this.data.userInfo.id,
      roomId: this.data.roomInfo.id
    })

    this.setData({ loading: true })

    wx.request({
      url: `${app.globalData.baseUrl}/api/accounting/user-settlement`,
      method: 'GET',
      data: {
        user_id: this.data.userInfo.id,
        room_id: this.data.roomInfo.id
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({
            settlementData: res.data.data,
            hasSettlement: true
          })
        } else {
          console.log('结算数据获取失败:', res.data.message)
          wx.showModal({
            title: '结算失败',
            content: res.data.message || '获取结算数据失败',
            showCancel: true,
            cancelText: '返回房间',
            confirmText: '重试',
            success: (modalRes) => {
              if (modalRes.confirm) {
                // 用户选择重试
                this.getSettlementData()
              } else {
                // 用户选择返回房间
                wx.navigateBack({
                  delta: 1
                })
              }
            }
          })
        }
      },
      fail: (err) => {
        console.error('获取结算数据失败:', err)
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      },
      complete: () => {
        this.setData({ loading: false })
      }
    })
  },

  // 生成结算策略
  generateSettlementStrategy() {
    if (!this.data.settlementData) {
      wx.showToast({
        title: '请先获取结算数据',
        icon: 'none'
      })
      return
    }

    wx.showModal({
      title: '发送结算到房间',
      content: '确定要将结算结果发送到房间吗？所有玩家都能看到结算详情。',
      success: (res) => {
        if (res.confirm) {
          this.sendSettlementToRoom()
        }
      }
    })
  },

  // 发送结算结果到房间
  sendSettlementToRoom() {
    if (!this.data.userInfo || !this.data.roomInfo) {
      wx.showToast({
        title: '缺少必要信息',
        icon: 'none'
      })
      return
    }

    wx.showLoading({ title: '发送中...' })

    wx.request({
      url: `${app.globalData.baseUrl}/api/accounting/send-settlement-to-room`,
      method: 'POST',
      data: {
        room_id: this.data.roomInfo.id,
        user_id: this.data.userInfo.id
      },
      success: (res) => {
        if (res.data.success) {
          wx.showToast({
            title: '结算已发送到房间',
            icon: 'success'
          })
          
          // 显示结算结果
          this.showSettlementResult(res.data.data.message)
        } else {
          wx.showToast({
            title: res.data.message || '发送失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('发送结算失败:', err)
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },

  // 显示结算结果
  showSettlementResult(message) {
    wx.showModal({
      title: '结算结果',
      content: message,
      showCancel: false,
      confirmText: '确定',
      success: () => {
        // 跳转回房间页面查看
        wx.navigateBack()
      }
    })
  },

  // 直接退房
  directCheckout() {
    wx.showModal({
      title: '确认退房',
      content: '确定要直接退房吗？',
      success: (res) => {
        if (res.confirm) {
          const RoomCache = require('../../utils/roomCache')
          RoomCache.clearRoom()
          
          wx.showToast({
            title: '已退房',
            icon: 'success'
          })
          
          setTimeout(() => {
            wx.navigateBack({
              delta: 1
            })
          }, 1500)
        }
      }
    })
  },

  // 查看房间结算
  viewRoomSettlement() {
    if (!this.data.roomInfo) {
      wx.showToast({
        title: '房间信息不存在',
        icon: 'none'
      })
      return
    }
    
    wx.navigateTo({
      url: `/pages/room-settlement/room-settlement?room_id=${this.data.roomInfo.id}`
    })
  },

  // 查看排行榜
  viewLeaderboard() {
    wx.navigateTo({
      url: '/pages/leaderboard/leaderboard'
    })
  },

  // 查看房间流水
  viewRoomFlow() {
    if (!this.data.roomInfo) {
      wx.showToast({
        title: '房间信息不存在',
        icon: 'none'
      })
      return
    }
    
    wx.navigateTo({
      url: `/pages/room-records/room-records?room_id=${this.data.roomInfo.id}`
    })
  },

  // 查看历史房间
  viewHistory() {
    wx.navigateTo({
      url: '/pages/room-history/room-history'
    })
  },

  // 使用手册
  viewManual() {
    wx.showModal({
      title: '使用手册',
      content: '1. 创建房间邀请好友\n2. 记录每局分数\n3. 生成个人结算单\n4. 查看房间总结算',
      showCancel: false,
      confirmText: '知道了'
    })
  }
})
